import sys
import re
import os

op_list = []
temp_list = []
operand_list = []

read_list = []
src = []
order = []

path = []
class Operand:
    op_count = 0

    def __init__(self, operand, data, dimensions, rank, elem_type, target_addr, target_capacity, has_cached, index, data_type):
        self.operand = operand
        self.data = data
        self.dimensions = dimensions
        self.rank = rank
        self.elem_type = elem_type
        self.target_addr = target_addr
        self.target_capacity = target_capacity
        self.has_cached = has_cached
        self.index = index
        self.data_type = data_type
        Operand.op_count += 1
# class Operand for the later develop, now it is not used.


def readfile(filename, file2):

    with open(filename, 'r') as f:
        # 1.search the useful info
        while 1:
            try:
                line = f.readline()
                if not line:
                    break
                # print line
                # extract the operand info
                if re.match('^op.*', line):
                    temp_list.append(line)
                if re.match('.*g fpga op.*', line):
                    temp_list.append(line)
                if re.match('^Pass.*', line):
                    line_split = line.split(' ')
                    path.append(line_split[4])

            except:
                pass

        # 2.preprocess the string
        for l in temp_list:
            # split the operand
            l_split = l.split(':')
            # strip unused symbol ,eg , '\n',space
            l_split[1] = l_split[1].strip('\n')
            l_split[1] = l_split[1].strip(' ')
            l_split[0] = l_split[0].strip(' ')

            operand_list.append(l_split)
        # list slice
        # index = operand_list.index('Dumping fpga operand')

        # print operand_list

        for i in range(0, operand_list.__len__(), 10):
            op_list.append(operand_list.__getslice__(i, i+10))

        # print(operand_list.__len__())

        for i in range(0, op_list.__len__()):
            op_list[i] = dict(op_list[i])
            # print op_list[i]

        for op in op_list:
            if op['op->data_type'] == 'FPGA_weight_identity':
                # print op['op->index']
                src.append(op['op->index'] + '/we.bin')
            if op['op->data_type'] == 'FPGA_weight':
                # print op['op->index']
                src.append(op['op->index'] + '/w.bin')
        # Convert to dict (method 1)
        # dict_op = dict(operand_list)
        # Convert to dict (method 2)
        # for op in operand_list:
        #    dict_op[op[0]] = op[1]

        # produce a result
        # write the result into the xml file

        # cmd = 'pwd'
        # path = os.popen(cmd).readlines()
        path[0] = path[0].strip('\n')
        # print path

        src.sort()
        for s in src:
            s = s.strip('012345')
            s = './' + path[0] + s
            order.append(s)

        # print src
        # print order

        source = ";".join(order)
        # source.split(';')

        # print source
        # src.split(';')
    # write the string to the xml
    with open(file2, 'r') as dec:

        dec_read = dec.readlines()

        for line in dec_read:
            if re.match('.*dir_weightfile.*', line):
                # print line
                line = '   <dir_weightfile>' + source + '<\dir_weightfile>\n'
                read_list.append(line)
                # read_list.append(line.replace('zcq', 'we'))
            else:
                read_list.append(line)

        dec = open(file2, 'w')
        dec.writelines(read_list)
        dec.flush()
        dec.close()


# argv[1] = pylog with debug info
# argv[2] = xml to correct the weight
readfile(sys.argv[1], sys.argv[2])
